<template>
  <el-container class="elheight">
    <el-aside class="appTree">
      <app-tree v-bind:tree-data="treeData" v-on:appTreeClick="treeClickHandle"></app-tree>
    </el-aside>
    <el-main>
      <el-container>
        <el-header class="dzy-main-header">
          <div class="btn-group-el">
            <btn-group :currentSelectedData="currentSelectedData" @btnClickCallback="btnClickCallback"></btn-group>
          </div>
          <div class="dzy-custom-search-box">
            <div>网格层级：
              <el-select v-model="queryData.levelCode" clearable placeholder="请选择">
                <el-option v-for="(item,index) in gridOption" :key="index" :label="item.name" :value="item.code"></el-option>
              </el-select>
            </div>
            <div>网格名称：<el-input placeholder="请输入网格名称" v-model="queryData.name"  clearable class="dzy-custom-input"></el-input></div>
            <div>网格编号：<el-input placeholder="请输入网格编号" v-model="queryData.gridCode" clearable class="dzy-custom-input"></el-input></div>
            <div>网格长姓名：<el-input placeholder="请输入网格长姓名" v-model="queryData.gridUserName"  clearable class="dzy-custom-input"></el-input></div>
            <div><el-button @click="searchHandleClick" type="primary" icon="el-icon-search">查询</el-button></div>
          </div>
        </el-header>
        <el-main>
          <app-table
            :page-data="pageData"
            :table-columns="tableColumns"
            v-on:currentChange="handleCurrentChange"
            v-on:handleCheckedRows="handleCheckedRows" />
          <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" :before-close="cancel">
            <el-form :model="formData" :rules="rules" ref="formData" :disabled="showOnly" label-width="120px" size="mini">
              <el-form-item label="名称" prop="name">
                <el-input v-model="formData.name" placeholder="请输入网格分类名称"></el-input>
              </el-form-item>
              <el-form-item label="上级网格" prop="gridIdArr">
                <div class="block">
                  <el-cascader
                    placeholder="请选择"
                    :options="treeData"
                    :props="gridIdProps"
                    filterable
                    clearable
                    change-on-select
                    :show-all-levels="false"
                    v-model="formData.gridIdArr"
                    @change="gridChangedEvt">
                  </el-cascader>
                </div>
              </el-form-item>
              <el-form-item label="网格编号" prop="gridCode">
                <el-input v-model="formData.gridCode" placeholder="请输入网格编号"></el-input>
              </el-form-item>
              <el-form-item label="网格长">
                <el-select v-model="formData.leaderUserId" filterable remote :loading="queryAppuserStatus" :remote-method="queryAppuser" placeholder="请选择网格长" clearable>
                  <el-option v-if="this.allUserData.length === 1" :value="this.allUserData[0].id" :label="this.allUserData[0].name"></el-option>
                  <el-option v-else v-for="item in allUserData" :key="item.id" :value="item.id" :label="item.name"></el-option>
                </el-select>
                <span style="font-size:1px;color:red;">* 请输入网格长名称</span>
              </el-form-item>
              <el-form-item label="网格户数">
                <el-input v-model="formData.familyNum" placeholder="请输入网格户数"></el-input>
              </el-form-item>
              <el-form-item label="网格面积(平方米)">
                <el-input v-model="formData.gridArea" placeholder="请输入网格面积"></el-input>
              </el-form-item>
              <el-form-item label="固定电话">
                <el-input v-model="formData.telephone" placeholder="请输入固定电话"></el-input>
              </el-form-item>
            </el-form>
            <div v-if="!showOnly" slot="footer" class="dialog-footer">
              <el-button @click="cancel('formData')">取 消</el-button>
              <el-button type="primary" @click="save('formData')" >提 交</el-button>
            </div>
          </el-dialog>
          <el-dialog :visible.sync="showMap" title="划网格" width="70%" top="8vh" :before-close="mapCancel" class="custom-map-dialog">
            <edit-map v-if="mapHackReset" mode="full" @appMapCallback="appMapCallback" :row-id="currentSelectedRowId" :target="mapTarget" ></edit-map>
          </el-dialog>
        </el-main>
      </el-container>
    </el-main>
  </el-container>
</template>

<script>
import CascaderTree from '@/components/CascaderTree'
import AppTree from '@/components/common/AppTree'
import BtnGroup from '@/components/BtnGroup'
import AppTable from '@/components/AppTable'
import EditMap from '@/components/EditMap'
import {getDictDataOption} from '@/utils/getDictDataOption'
import {getAllRegion} from '@/utils/region'
import {getUserGridTree, setUserGridTree, setUserRegionTree, getUserRegionTree} from '@/utils/LocalDataUtil'
import {findGrid, findGridTree, createGrid, updateGrid, deleteGrid, createMapLocation, getUserList, getGridTree} from '@/http/AppApi'
export default {
  data () {
    return {
      tableData: [],
      pageData: {},
      formData: {
        parentId: '',
        name: '',
        gridCode: '',
        leaderUserId: '',
        familyNum: '',
        gridArea: '',
        telephone: ''
      },
      queryData: {},
      allUserData: [],
      treeData: [],
      regionTreeData: [],
      dialogTitle: '',
      currentSelectedRowId: '',
      dialogFormVisible: false,
      currentSelectedData: [],
      showOnly: false,
      showMap: false,
      mapTarget: {},
      mapHackReset: false,
      tableColumns: [
        { label: '网格名称', prop: 'name' },
        { label: '网格编号', prop: 'gridCode' },
        { label: '网格长', prop: 'appUserName' },
        { label: '网格长联系方式', prop: 'phone' }
      ],
      rules: {
        gridIdArr: [{
          required: true,
          message: '请选择上级网格',
          trigger: 'blur'
        }],
        name: [{
          required: true,
          message: '请输入网格分类名称',
          trigger: 'blur'
        }],
        gridCode: [{
          required: true,
          message: '请输入网格编号',
          trigger: 'blur'
        }]
      },
      gridIdProps: {
        label: 'name',
        value: 'id'
      },
      gridOption: [],
      queryAppuserStatus: false
    }
  },
  components: {
    AppTree,
    BtnGroup,
    AppTable,
    EditMap,
    CascaderTree
  },
  mounted () {
    this.getTableData()
    this.getLocalTreeData()
    this.getRetionTreeData()
    this.gridOption = getDictDataOption('网格层级')
  },
  methods: {
    save (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.formData) {
            if (!this.beforeSubmit()) {
              return
            }
            if (this.formData.gridIdArr && this.formData.gridIdArr.length > 0) {
              let len = this.formData.gridIdArr.length - 1
              this.formData.parentId = this.formData.gridIdArr[len]
            }
            if (this.formData.id) {
              updateGrid(this.formData).then(resp => {
                if (resp.code && resp.code === '200') {
                  this.getTableData()
                  this.reloadTreeData()
                  this.dialogFormVisible = false
                  this.$message({
                    showClose: true,
                    message: '修改成功',
                    type: 'success'
                  })
                } else {
                  this.$message({
                    type: 'info',
                    message: resp.message
                  })
                }
              })
            } else {
              createGrid(this.formData).then(resp => {
                if (resp.code && resp.code === '200') {
                  this.getTableData()
                  this.dialogFormVisible = false
                  this.reloadTreeData()
                  this.$message({
                    showClose: true,
                    message: '新增成功',
                    type: 'success'
                  })
                } else {
                  this.$message({
                    type: 'info',
                    message: resp.message
                  })
                }
              })
            }
          }
        } else {
          return false
        }
      })
    },
    del (rows) {
      if (rows && rows instanceof Array && rows.length > 0) {
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          rows.forEach(row => {
            deleteGrid(row).then(resp => {
              if (resp.code && resp.code === '200') {
                this.getTableData()
                this.reloadTreeData()
                this.$message({
                  showClose: true,
                  message: '删除成功',
                  type: 'success'
                })
              } else {
                this.$message({
                  type: 'info',
                  message: resp.message
                })
              }
            })
          })
        })
      }
    },
    cancel (formName) {
      this.mapCancel()
      this.dialogFormVisible = false
      this.formData = {}
      this.showMap = false
      this.mapHackReset = false
      if (this.$refs[formName] !== undefined) {
        this.$refs[formName].resetFields()
      }
    },
    getTableData () {
      let param = this.queryData
      findGrid(param).then(resp => {
        if (resp.code && resp.code === '200') {
          let data = resp.data
          if (data) {
            this.pageData = data
            if (this.pageData.items && this.pageData.items instanceof Array) {
              this.tableData = this.pageData.items
            }
          }
        }
      })
    },
    handleCurrentChange (val) {
      this.queryData.offset = (val - 1) * 10
      this.getTableData()
    },
    getTreeData () {
      getGridTree().then(resp => {
        if (resp.code && resp.code === '200') {
          let data = resp.data
          if (data) {
            this.treeData = data
          }
        }
      })
    },
    getLocalTreeData () {
      let data = getUserGridTree()
      if (data && data instanceof Array) {
        this.treeData = data
      }
    },
    getRetionTreeData () {
      let regionTreeData = getUserRegionTree()
      if (regionTreeData && regionTreeData instanceof Array) {
        this.regionTreeData = regionTreeData
      }
    },
    reloadTreeData () {
      findGridTree().then(resp => {
        if (resp.code && resp.code === '200') {
          let data = resp.data
          if (data && data instanceof Array) {
            setUserGridTree(data)
            setUserRegionTree(data)
            this.treeData = data
          }
        }
      })
    },
    beforeSubmit () {
      return true
    },
    treeClickHandle (data) {
      this.queryData = {}
      this.queryData.likeParentId = data.id
      let gridData = {}
      gridData.id = data.id
      gridData.items = this.treeData
      let gridIdArr = getAllRegion(gridData)
      this.$set(this.formData, 'gridIdArr', gridIdArr)
      this.getTableData()
    },
    btnClickCallback (callbackData) {
      if (callbackData.btnType === 'delete') {
        this.dialogFormVisible = false
        let rows = callbackData.rows
        this.del(rows)
      } else if (callbackData.btnType === 'draw') {
        let rowData = callbackData.rows[0]
        if (rowData) {
          this.mapHackReset = true
          this.showMap = true
          let target = {}
          target.targetId = rowData.id
          target.targetType = 'grid'
          this.mapTarget = target
        }
      } else {
        // this.getAllUserData()
        if (callbackData.btnType === 'post') {
          if (this.formData.gridIdArr && this.formData.gridIdArr.length > 0) {
            let arr = this.formData.gridIdArr
            this.formData = {}
            this.$set(this.formData, 'gridIdArr', arr)
            this.gridChangedEvt(arr)
          }
        } else {
          let obj = JSON.stringify(callbackData.rows[0])
          this.formData = JSON.parse(obj)
          let gridData = {}
          gridData.id = this.formData.parentId
          gridData.items = this.treeData
          let gridIdArr = getAllRegion(gridData)
          this.$set(this.formData, 'gridIdArr', gridIdArr)
          this.allUserData = []
          let user = {}
          user.name = this.formData.gridUserName
          user.id = this.formData.leaderUserId
          this.formData.leaderUserId = user.id
          this.allUserData.push(user)
        }
        this.showOnly = callbackData.sohwOnly
        this.dialogTitle = callbackData.dialogTitle
        this.dialogFormVisible = true
      }
    },
    gridChangedEvt (val) {
      if (val instanceof Array && val.length > 0) {
        let len = val.length - 1
        let pid = val[len]
        if (pid === '0') {
          this.$set(this.formData, 'gridCode', '')
          return ''
        }
        let data = {}
        data.isGetGridCode = true
        data.items = this.treeData
        data.id = pid
        let gridCode = getAllRegion(data)
        // 判断网格编号是否是最底层等级
        if (gridCode.substring(gridCode.length - 9) === 'undefined') {
          this.$set(this.formData, 'gridIdArr', '')
          this.$set(this.formData, 'gridCode', '')
          this.$message({showClose: true, message: '不能选择最底层网格！', type: 'error'})
          return
        }
        this.$set(this.formData, 'gridCode', gridCode)
      } else {
        this.$set(this.formData, 'gridCode', '')
      }
    },
    handleCheckedRows (rows) {
      if (rows && rows instanceof Array && rows.length > 0) {
        this.currentSelectedData = rows
        this.formData = rows[0]
        this.currentSelectedRowId = rows[0].id
      } else {
        this.currentSelectedData = []
        this.formData = {}
      }
    },
    appMapCallback (appMapInfo) {
      if (appMapInfo.target) {
        let mapLocation = {}
        mapLocation.targetId = appMapInfo.target.targetId
        mapLocation.targetType = appMapInfo.target.targetType
        if (appMapInfo.clearStatus) {
          mapLocation.clearStatus = appMapInfo.clearStatus
        }
        if (appMapInfo.markPosition) {
          mapLocation.longitude = appMapInfo.markPosition.lng
          mapLocation.latitude = appMapInfo.markPosition.lat
        }
        if (appMapInfo.polyPathArr) {
          mapLocation.mapArea = appMapInfo.polyPathArr
          mapLocation.mapColor = appMapInfo.polyColor
        }
        createMapLocation(mapLocation).then(resp => {
          if (resp.code && resp.code === '200') {
            console.log('保存成功')
          }
        })
      }
      // this.mapCancel()
    },
    mapCancel () {
      this.mapHackReset = false
      this.showMap = false
    },
    searchHandleClick () {
      this.queryData.offset = 0
      this.getTableData()
    },
    getAllUserData () {
      getUserList().then(resp => {
        if (resp.code && resp.code === '200') {
          let data = resp.data
          if (data && data instanceof Array) {
            this.allUserData = data
          }
        }
      })
    },
    handelChangeRegion (data) {
      console.log(data)
    },
    queryAppuser (query) {
      if (query && query !== '') {
        this.queryAppuserStatus = true
        let param = {name: query}
        getUserList(param).then(resp => {
          this.queryAppuserStatus = false
          if (resp.code && resp.code === '200') {
            let data = resp.data
            if (data && data instanceof Array) {
              this.allUserData = data
            }
          }
        })
      }
      return []
    }
  },
  computed: {},
  watch: {}
}
</script>
<style scoped>

</style>
